package cn.com.homeyoda.aimate.aihealth.ui.health.frragment;

import static com.wzq.mvvmsmart.utils.Utils.getContext;

import android.content.Context;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartView;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAMarker;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotLinesElement;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis;
import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor;
import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.bean.ChronicDiseaseItemBean;
import cn.com.homeyoda.aimate.aihealth.bean.InspectionScheduleTypeBean;
import cn.com.homeyoda.aimate.aihealth.bean.MyselfPlanBean;
import cn.com.homeyoda.aimate.aihealth.bean.PopularListBean;
import cn.com.homeyoda.aimate.aihealth.manager.UserInfoManager;
import cn.com.homeyoda.aimate.aihealth.ui.detail.DetailActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.ChronicDiseaseActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.ChronicDiseaseAddActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.SportPlanActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.VideoPlayActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.ChroicDiseaseTitleAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.DailyKepuAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.WeekCourseAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.WeekSelectAdapter;
import cn.com.homeyoda.aimate.aihealth.views.SpaceItemDecoration;

/**
 * 慢病管理
 */
public class ChronicDiseaseFragment extends Fragment {
    private ChronicDiseaseActivity mActivity;


    private ChroicDiseaseTitleAdapter sportPlanTitleAdapter;
    private DailyKepuAdapter dailyKepuAdapter;

    private View mRootView, btnEdit, clOutsideBloodPressure, clOutsideHeartRate, clBloodPressure;

    private RecyclerView rvDisease, rvDailyKepu;

    private FrameLayout aaChartContainer, aaChartContainer2;

    private TextView tvMeasureTime, titleSystolic, titleDiastolic, titleHeart, tvSystolicPressure, tvDiastolicPressure, tvHearte, tvSystolicTips;

    private boolean initViewObservable = false;
    private boolean needUpdataUi = false;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (ChronicDiseaseActivity) context;

        if (!initViewObservable) {
            initViewObservable();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_chronic_disease, container, false);
            initView();
        }

        return mRootView;
    }


    private void initView() {
        btnEdit = mRootView.findViewById(R.id.btn_edit);
        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.changeChronicDiseaseAddFragment();
            }
        });

        aaChartContainer = mRootView.findViewById(R.id.aa_chart_container);
        aaChartContainer2 = mRootView.findViewById(R.id.aa_chart_container2);

        tvMeasureTime = mRootView.findViewById(R.id.tv_measure_time);
        titleSystolic = mRootView.findViewById(R.id.title_Systolic);
        titleDiastolic = mRootView.findViewById(R.id.title_Diastolic);
        titleHeart = mRootView.findViewById(R.id.title_heart);
        tvSystolicPressure = mRootView.findViewById(R.id.tvSystolicPressure);
        tvDiastolicPressure = mRootView.findViewById(R.id.tvDiastolicPressure);
        tvHearte = mRootView.findViewById(R.id.tvHearte);
        clOutsideBloodPressure = mRootView.findViewById(R.id.cl_outside_blood_pressure);
        clOutsideHeartRate = mRootView.findViewById(R.id.cl_outside_heart_rate);
        clBloodPressure = mRootView.findViewById(R.id.cl_blood_pressure);
        tvSystolicTips = mRootView.findViewById(R.id.tvSystolicTips);

        rvDisease = mRootView.findViewById(R.id.rv_disease);
        rvDailyKepu = mRootView.findViewById(R.id.rv_daily_kepu);
        initRecyclerView();
    }

    private void initRecyclerView() {
        sportPlanTitleAdapter = new ChroicDiseaseTitleAdapter(R.layout.item_sport_plan_title, new ArrayList<>(), mActivity);
        rvDisease.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
        rvDisease.setAdapter(sportPlanTitleAdapter);

        sportPlanTitleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                sportPlanTitleAdapter.setSelectPosition(position);
                mActivity.getViewModel().setTitleSelectPosition(position);
            }
        });


        List<PopularListBean.RowsBean> kepuData = UserInfoManager.getInstance().getKePuData();
        dailyKepuAdapter = new DailyKepuAdapter(R.layout.item_daily_kepu, kepuData, mActivity);
        rvDailyKepu.setLayoutManager(new GridLayoutManager(mActivity, 2));
        rvDailyKepu.addItemDecoration(new SpaceItemDecoration(0, 0, 20, 24));
        rvDailyKepu.setAdapter(dailyKepuAdapter);

        dailyKepuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mActivity, DetailActivity.class);
                intent.putExtra("id", dailyKepuAdapter.getData().get(position).getId());
                startActivity(intent);
            }
        });

    }


    private void aaChartView(List<Integer> systolic, List<Integer> diastolic, String[] times) {
        aaChartContainer.removeAllViews();
        AAChartView aaChartView = new AAChartView(getContext());
        aaChartContainer.addView(aaChartView);
        aaChartView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.divider_transparent));
        aaChartView.setIsClearBackgroundColor(true);

        Object[][] blueStopsArr = new Object[][]{
                {0.0, "#00BFFF00"},
                {0.5, "#00BFFF00"},
                {1.0, "#00BFFF1A"},
        };

        Map<String, Object> gradientBlueColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                blueStopsArr
        );

        Object[][] redStopsArr = new Object[][]{
                {0.0, "#FF8C0000"},
                {0.5, "#FF8C0000"},
                {1.0, "#FF8C001A"},
        };

        Map<String, Object> gradientRedColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                redStopsArr
        );

        // 配置 AAChartModel
        AAChartModel aaChartModel = new AAChartModel()
                .chartType(AAChartType.Areaspline)
                .title("")
                .dataLabelsEnabled(false)
                .markerRadius(0)
                .yAxisTitle("")
                .legendEnabled(false)
                .yAxisGridLineWidth(0f)
                .tooltipEnabled(false)
                .dataLabelsStyle(new AAStyle().color("#000000CC").fontSize(20f))
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("收缩压")
                                .color("#00BFFF")
                                .lineWidth(2f)
                                .fillColor(gradientBlueColorDic)
                                .fillOpacity(0.5f)
                                .data(diastolic.toArray())
                                .enableMouseTracking(false) // 禁用鼠标跟踪
                                .showInLegend(false)        // 不在 legend 中显示
                                .marker(new AAMarker().enabled(false)) // 不显示 marker 点
                        ,

                        new AASeriesElement()
                                .name("舒张压")
                                .color("#FF8C00")
                                .lineWidth(2f)
                                .fillColor(gradientRedColorDic)
                                .data(systolic.toArray())
                                .enableMouseTracking(false) // 禁用鼠标跟踪
                                .showInLegend(false)        // 不在 legend 中显示
                                .marker(new AAMarker().enabled(false)) // 不显示 marker 点
                });

        // 设置辅助线
        AAOptions aaOptions = aaChartModel.aa_toAAOptions();
        aaOptions.chart(new AAChart().type(aaChartModel.chartType).marginTop(20));
        aaOptions.xAxis(new AAXAxis()
                        .tickInterval(2)
                        .categories(times)
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#000000CC")
                                        .fontSize(12f)
                                )
                                .x(20f)
                                .y(40f)
                        )
                )
                .yAxis(new AAYAxis()
                        .min(0)
                        .max(150)
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#00000066")
                                        .fontSize(18f)
                                        .textAlign("right")
                                )
                                .x(5f)
                                .y(-2f)
                        )
                        .tickInterval(30)
                        .offset(10f)
                        .gridLineColor("#6C7B8A1A")
                        .gridLineWidth(1f)
                        .title(new AATitle().text(""))
                        .plotLines(new AAPlotLinesElement[]{
                                new AAPlotLinesElement().color("#FF3333").dashStyle(AAChartLineDashStyleType.ShortDash).value(135).width(2f),
                                new AAPlotLinesElement().color("#5ECFAC").dashStyle(AAChartLineDashStyleType.ShortDash).value(115).width(2f),
                                new AAPlotLinesElement().color("#FF3A79").dashStyle(AAChartLineDashStyleType.ShortDash).value(90).width(2f),
                                new AAPlotLinesElement().color("#0065FF").dashStyle(AAChartLineDashStyleType.ShortDash).value(60).width(2f),
                        }));

        // 渲染图表
        aaChartView.aa_drawChartWithChartOptions(aaOptions);
    }

    private void aaChartView(List<Integer> heart, String[] times) {
        aaChartContainer2.removeAllViews();
        AAChartView aaChartView = new AAChartView(getContext());
        aaChartContainer2.addView(aaChartView);
        aaChartView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.divider_transparent));
        aaChartView.setIsClearBackgroundColor(true);

        Object[][] blueStopsArr = new Object[][]{
                {0.0, "#00BFFF00"},
                {0.5, "#00BFFF00"},
                {1.0, "#00BFFF1A"},
        };

        Map<String, Object> gradientBlueColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                blueStopsArr
        );

        Object[][] redStopsArr = new Object[][]{
                {0.0, "#FF8C0000"},
                {0.5, "#FF8C0000"},
                {1.0, "#FF8C001A"},
        };

        Map<String, Object> gradientRedColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                redStopsArr
        );

        // 配置 AAChartModel
        AAChartModel aaChartModel = new AAChartModel()
                .chartType(AAChartType.Areaspline)
                .title("")
                .dataLabelsEnabled(false)
                .markerRadius(0)
                .yAxisTitle("")
                .legendEnabled(false)
                .yAxisGridLineWidth(0f)
                .tooltipEnabled(false)
                .dataLabelsStyle(new AAStyle().color("#000000CC").fontSize(20f))
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("心率")
                                .color("#00BFFF")
                                .lineWidth(2f)
                                .fillColor(gradientBlueColorDic)
                                .fillOpacity(0.5f)
                                .data(heart.toArray())
                                .enableMouseTracking(false) // 禁用鼠标跟踪
                                .showInLegend(false)        // 不在 legend 中显示
                                .marker(new AAMarker().enabled(false)) // 不显示 marker 点
                });

        // 设置辅助线
        AAOptions aaOptions = aaChartModel.aa_toAAOptions();
        aaOptions.chart(new AAChart().type(aaChartModel.chartType).marginTop(20));
        aaOptions.xAxis(new AAXAxis()
                        .tickInterval(2)
                        .categories(times)
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#000000CC")
                                        .fontSize(12f)
                                )
                                .x(20f)
                                .y(40f)
                        )
                )
                .yAxis(new AAYAxis()
                        .min(0)
                        .max(150)
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#00000066")
                                        .fontSize(18f)
                                        .textAlign("right")
                                )
                                .x(5f)
                                .y(-2f)
                        )
                        .tickInterval(30)
                        .offset(10f)
                        .gridLineColor("#6C7B8A1A")
                        .gridLineWidth(1f)
                        .title(new AATitle().text(""))
                        .plotLines(new AAPlotLinesElement[]{
                                new AAPlotLinesElement().color("#FF3333").dashStyle(AAChartLineDashStyleType.ShortDash).value(135).width(2f),
                                new AAPlotLinesElement().color("#5ECFAC").dashStyle(AAChartLineDashStyleType.ShortDash).value(60).width(2f),
                        }));

        // 渲染图表
        aaChartView.aa_drawChartWithChartOptions(aaOptions);
    }


    public void initViewObservable() {

        if (mActivity == null) {
            return;
        }

        initViewObservable = true;

        mActivity.getViewModel().visualLiveData.observe(mActivity, visual -> {
            if (visual.size() > 0 && mActivity.getViewModel().defTitle != null) {

                InspectionScheduleTypeBean.DataBean topBean = visual.get(0);
                tvMeasureTime.setText(topBean.getAddTime());

                if (mActivity.getViewModel().defTitle.getType().equals("2")) {
                    // 高血压
                    titleSystolic.setVisibility(View.VISIBLE);
                    titleDiastolic.setVisibility(View.VISIBLE);
                    titleHeart.setVisibility(View.GONE);

                    tvSystolicPressure.setVisibility(View.VISIBLE);
                    tvDiastolicPressure.setVisibility(View.VISIBLE);
                    tvHearte.setVisibility(View.GONE);

                    clOutsideBloodPressure.setVisibility(View.VISIBLE);
                    clOutsideHeartRate.setVisibility(View.GONE);

                    tvSystolicPressure.setText(topBean.getSystolicPressure() + "");
                    tvDiastolicPressure.setText(topBean.getDiastolicPressure() + "");

                    if (topBean.getSystolicPressure() > topBean.getSystolicValueMax()
                            || topBean.getDiastolicPressure() > topBean.getDiastolicValueMax()) {
                        // 血压偏高
                        clBloodPressure.setBackgroundResource(R.mipmap.bg_blood_pressure_height);
                        tvSystolicTips.setVisibility(View.VISIBLE);
                    } else {
                        // 血压正常
                        clBloodPressure.setBackgroundResource(R.mipmap.bg_blood_pressure_normal);
                        tvSystolicTips.setVisibility(View.GONE);
                    }

                    List<Integer> systolic = new ArrayList<>();
                    List<Integer> diastolic = new ArrayList<>();
                    List<String> times = new ArrayList();

                    for (InspectionScheduleTypeBean.DataBean item : visual) {
                        systolic.add(item.getSystolicPressure());
                        diastolic.add(item.getDiastolicPressure());
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            try {
                                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                                Date date = inputFormat.parse(item.getAddTime());
                                SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd", Locale.getDefault());
                                String yearMonth = outputFormat.format(date);
                                times.add(yearMonth);
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }

                    aaChartView(systolic, diastolic, times.toArray(new String[0]));
                } else if (mActivity.getViewModel().defTitle.getType().equals("1")) {
                    // 冠心病
                    titleSystolic.setVisibility(View.GONE);
                    titleDiastolic.setVisibility(View.GONE);
                    titleHeart.setVisibility(View.VISIBLE);

                    tvSystolicPressure.setVisibility(View.GONE);
                    tvDiastolicPressure.setVisibility(View.GONE);
                    tvHearte.setVisibility(View.VISIBLE);

                    tvHearte.setText(topBean.getHeart() + "");

                    clOutsideBloodPressure.setVisibility(View.GONE);
                    clOutsideHeartRate.setVisibility(View.VISIBLE);

                    if (topBean.getHeart() > topBean.getValueMax()) {
                        // 心率过高
                        clBloodPressure.setBackgroundResource(R.mipmap.bg_blood_pressure_height);
                        tvSystolicTips.setVisibility(View.VISIBLE);
                        tvSystolicTips.setText("您近期心率偏高，建议持续用药");
                    } else {
                        clBloodPressure.setBackgroundResource(R.mipmap.bg_blood_pressure_normal);
                        tvSystolicTips.setVisibility(View.GONE);
                    }

                    List<Integer> heart = new ArrayList<>();
                    List<String> times = new ArrayList();

                    for (InspectionScheduleTypeBean.DataBean item : visual) {
                        heart.add(item.getHeart());
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            try {
                                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                                Date date = inputFormat.parse(item.getAddTime());
                                SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd", Locale.getDefault());
                                String yearMonth = outputFormat.format(date);
                                times.add(yearMonth);
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }

                    aaChartView(heart, times.toArray(new String[0]));
                }
            }
        });

        mActivity.getViewModel().diseaseTitleList.observe(mActivity, titles -> {
            if (sportPlanTitleAdapter != null) {
                sportPlanTitleAdapter.setNewData(mActivity.getViewModel().diseaseTitleList.getValue());
                mActivity.getViewModel().setTitleSelectPosition(sportPlanTitleAdapter.getSelectPosition());
            }
        });


    }

}
